<template>
  <van-sticky>
      <van-nav-bar
          :title="product.name"
          left-text="返回"
          left-arrow
          @click-left="onBack"
      >
      </van-nav-bar>
  </van-sticky>

  <van-swipe :autoplay="3000" lazy-render>
      <van-swipe-item
          v-for="(image, index) in product.thumbs_cdn"
          :key="index"
      >
          <van-image width="100%" height="200px" fit="cover" :src="image" />
      </van-swipe-item>
  </van-swipe>

  <div class="detailbox">
      <h4>{{ product.name }}</h4>
      <div class="price">
          单独购买：<em>￥</em>{{ product.price }} | 拼团价格：<em>￥</em
          >{{ product.team }}
      </div>
  </div>

  <div class="allkbox"></div>

  <!-- 商品规格 -->
  <div class="info_choice">
      <!-- Sku 商品规格 -->
      <div class="commodity" @click="SkuShow = true">
          <div class="opt">
              <div class="title wanl-gray">选择</div>
              <div class="option">
                  <div class="selected">
                      <div>
                          <span>尺码</span>
                          |
                          <span>颜色</span>
                      </div>
                  </div>
              </div>
          </div>
          <div class="wanl-gray">
              <img src="/assets/images/go.png" />
          </div>
      </div>
      <!-- 服务 -->
      <div class="commodity" @click="TipShow = true">
          <div class="opt">
              <div class="title wanl-gray">服务</div>
              <div class="option">
                  <div class="selected">
                      <div>
                          <span>7天无理由退款</span>
                          <span>·</span>
                          <span>24小时内发货</span>
                          <span>·</span>
                          <span>假一赔十</span>
                      </div>
                  </div>
              </div>
          </div>
          <div class="wanl-gray">
              <img src="/assets/images/go.png" />
          </div>
      </div>
  </div>

  <div class="allkbox"></div>

  <!-- 选项卡 -->
  <van-tabs v-model:active="TabActive" type="card" color="#EE0A24">
      <van-tab title="产品参数">
          <div v-html="product.content"></div>
      </van-tab>
      <van-tab title="商品评价">
          <div class="rate" style="overflow-x: hidden">
              <div class="rate-header">
                  <div class="rate-score">
                      <h4>与描述相符</h4>
                      <strong>4.5</strong>
                  </div>
                  <div class="rate-graph">
                      <van-rate v-model="rate" allow-half readonly />
                  </div>
              </div>

              <div class="rate-content">
                  <div v-if="comment">
                      <div
                          class="review-box"
                          v-for="(item, key) in comment"
                          :key="key"
                      >
                          <div class="review-item">
                              <!-- 评论人 -->
                              <div class="from-whom">
                                  <div class="avatar">
                                      <img
                                          :src="item.business.avatar_text"
                                          alt=""
                                      />
                                  </div>
                                  <div class="name">
                                      {{
                                          item.business.nickname
                                              ? item.business.nickname
                                              : '暂无昵称'
                                      }}
                                  </div>
                              </div>

                              <!-- 评论内容 -->
                              <div class="review-details">
                                  <div class="content">
                                      {{ item.comment }}
                                  </div>
                                  <div>
                                      <img :src="item.thumbs_text" alt="" />
                                  </div>
                                  <div class="time">
                                      {{ item.comtime_text }}
                                  </div>
                                  <van-rate v-model="item.rate" readonly />
                              </div>
                          </div>
                      </div>
                  </div>
                  <div v-else>
                      <div class="rate-empty">该商品还没有人写评价呢</div>
                  </div>
              </div>
          </div>
      </van-tab>
  </van-tabs>

  <!-- SKU -->
  <van-sku
      ref="SkuRef"
      v-model="SkuShow"
      :sku="sku"
      :properties="properties"
      :goods="goods"
      :goods-id="product.id"
      @add-cart="onAddCart"
      @buy-clicked="onBuy"
  >
      <template #sku-actions="props">
          <div class="van-sku-actions">
              <van-button
                  square
                  size="large"
                  type="warning"
                  @click="props.skuEventBus.emit('sku:addCart')"
                  >加入购物车</van-button
              >

              <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
              <van-button
                  square
                  size="large"
                  type="danger"
                  @click="props.skuEventBus.emit('sku:buy')"
                  >单独购买</van-button
              >

              <van-button square size="large" type="danger" @click="JoinTeam"
                  >参与拼团</van-button
              >
          </div>
      </template>
  </van-sku>

  <!-- 协议条款 -->
  <van-action-sheet v-model:show="TipShow" title="协议条款">
      <div class="ProductTip">
          三、我们如何使用信息 <br />
          四、我们如何共享信息<br />
          五、我们如何转让信息<br />
          六、我们如何公开披露信息<br />
          七、一般储存期限<br />
          八、我们如何确保您的信息安全<br />
          九、您能做什么<br />
          十、我们如何处理未成年人的个人信息<br />
          十一、您的个人信息的存储地点<br />
          十二、本隐私权政策不适用的范围<br />
          十三、本隐私权政策如何更新<br />
          十四、联系我们<br />
      </div>
  </van-action-sheet>

  <!-- 底部导航栏 -->
  <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" />

      <van-action-bar-icon
          icon="cart-o"
          @click="ToCart"
          text="购物车"
          :badge="product.cart_count"
          v-if="product.cart_count"
      />
      <van-action-bar-icon
          icon="cart-o"
          @click="ToCart"
          text="购物车"
          v-else
      />

      <van-action-bar-icon
          icon="star"
          text="已收藏"
          color="#ff5000"
          @click="onCollection"
          v-if="product.collection_status"
      />
      <van-action-bar-icon
          icon="star-o"
          text="收藏"
          @click="onCollection"
          v-else
      />

      <van-action-bar-button
          type="danger"
          text="立即购买"
          @click="SkuShow = true"
      />
  </van-action-bar>
</template>

<script setup>
import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css';

const { proxy } = getCurrentInstance();

const proid = ref(proxy.$route.query.proid ?? 0);
const business = ref(
  proxy.$cookies.get('business') ? proxy.$cookies.get('business') : {}
);

// 商品数据
const product = ref({});

// sku 商品规格
const SkuShow = ref(false); // 显示商品规格弹出层
const SkuRef = ref(null); // 组件实例
const sku = ref({}); // 商品sku数据
const properties = ref([]); // 商品属性数据
const goods = ref({}); // 商品信息

// 服务条例
const TipShow = ref(false); // 显示服务条例弹出层

// 选项卡的选中值
const TabActive = ref(0);

// 商品总评分的平均值
const rate = ref(4.5);

// 商品评价数据
const comment = ref([]);

onBeforeMount(() => {
  getProductInfo();
});

const getProductInfo = async () => {
  let params = {
      proid: proid.value,
  };

  if (business.value.id) {
      params.busid = business.value.id;
  }

  let result = await proxy.$post({
      url: '/product/product/info',
      params,
  });

  if (result.code === 1) {
      let ProductData = result.data.product;
      let propertiesData = result.data.propertiesList;
      let SkuData = result.data.sku;

      product.value = ProductData;
      // sku
      sku.value = SkuData;

      // 商品信息
      goods.value = {
          // 商品图片
          picture: ProductData.thumb_cdn,
      };

      // 提取对象的值
      properties.value = Object.values(propertiesData);
  } else {
      proxy.$warnNotify({
          message: result.msg,
          onClose: () => {
              onBack();
          },
      });
  }
};

// 收藏
const onCollection = async () => {
  if (!business.value.id) {
      proxy
          .$showConfirm({
              title: '登录提示',
              message: '是否需要跳转登录页？',
          })
          .then(() => {
              proxy.$cookies.set(
                  'redirect',
                  '/product/product/info?proid=' + proid.value
              );

              proxy.$router.push({ path: '/business/base/login' });
          })
          .catch(() => {});

      return false;
  }

  let result = await proxy.$post({
      url: '/product/product/collection',
      params: {
          busid: business.value.id,
          proid: proid.value,
      },
  });

  if (result.code === 1) {
      if (result.msg === '取消收藏成功') {
          product.value.collection_status = false;
      } else {
          product.value.collection_status = true;
      }

      return false;
  } else {
      proxy.$warnNotify(result.msg);

      return false;
  }
};

// 去购物车
const ToCart = () => {
  proxy.$router.push({
      path: '/product/cart/index',
      query: { action: 'cart' },
  });
};

// 添加购物车
const onAddCart = async (skuData) => {
  if (!business.value.id) {
      proxy
          .$showConfirm({
              title: '登录提示',
              message: '是否需要跳转登录页？',
          })
          .then(() => {
              proxy.$cookies.set(
                  'redirect',
                  '/product/product/info?proid=' + proid.value
              );

              proxy.$router.push({ path: '/business/base/login' });
          })
          .catch(() => {});

      return false;
  }

  // 选择的商品属性
  let relation = skuData.selectedSkuComb;

  // 商品是有规格，但是加入购物车时没有选择相应规格
  if (properties.value.length > 0 && !relation) {
    proxy.$showToast({
            type:'fail',
            message:'请选择商品规格'
        });

      return false;
  }

  let num = skuData.selectedNum ?? 0;

  if (num <= 0) {
      proxy.$showToast('至少选择一件商品');

      return false;
  }

  let relationids = [];

  // 有规格
  if (properties.value.length > 0) {
      for (let item of relation.properties) {
          let id = item['v'][0] ? item['v'][0].id : 0;

          if (id) relationids.push(id);
      }
  }

  // 组装数据
  let params = {
      busid: business.value.id,
      num,
      relationids,
      proid: proid.value,
  };

  let result = await proxy.$post({
      url: '/product/cart/add',
      params,
  });

  if (result.code === 1) {
      SkuShow.value = false;
      proxy
          .$showConfirm({
              title: '跳转提示',
              message: '是否前往购物车进行结算？',
          })
          .then((result) => {
              proxy.$router.push({
                  path: '/product/cart/index',
                  query: { action: 'cart' },
              });
          })
          .catch((err) => {});

      return false;
  } else {
      proxy.$showToast(result.msg);

      return false;
  }
};

// 单独购买
const onBuy = () => {};

// 拼团
const JoinTeam = async () => {
    let teamid = proxy.$cookies.get('teamid');

    if(!teamid)
    {
        proxy.$router.push({path:'/product/team/index',query:{proid:proid.value}})

        return false;
    }

    if(!business.value.id)
    {
        proxy.$showConfirm({
            title: '登录提示',
            message: '是否需要跳转登录页？',
        }).then(() => {
            proxy.$cookies.set(
                'redirect',
                '/product/product/info?proid=' + proid.value
            );

            proxy.$router.push({ path: '/business/base/login' });
        }).catch(() => {});

        return false;
    }

    if(properties.value.length > 0 && !SkuRef.value.selectedSkuComb)
    {
        proxy.$showToast({
            type:'fail',
            message:'请选择商品规格'
        });

        return false;
    }

    let relationids = [];

    if(properties.value.length > 0)
    {
        let relation = SkuRef.value.selectedSkuComb.properties;

        for(let item of relation)
        {
            relationids.push(item['v'][0].id)
        }
    }

    proxy.$cookies.set('relationids',relationids.join(','));
    proxy.$cookies.set('num',SkuRef.value.selectedNum);

    proxy.$router.push({path:'/product/team/confirm',query:{proid:proid.value}});
}

const onBack = () => proxy.$router.back();
</script>
